//1.获取按钮
let toggele = document.querySelector("button");
//2.获取侧边栏
let nav = document.querySelector("nav");
//3.获取body
let body = document.querySelector("body");
//4.设置状态
let flag = true;

// let addUser = document.querySelector("aside>button");

let Newdata = [];

function clean() {
  $("main").innerHTML = `
  <h2>
  <strong>Person</strong>
  <span>Wealth</span>
  </h2> 
  `;
}

function $(id) {
  return document.getElementById(id);
}

//给按钮增加点击事件
toggele.addEventListener("click", function () {
  //判断
  if (flag == true) {
    body.className += "body show_nav";
    flag = false;
  } else {
    body.className = "body";
    flag = true;
  }
});
// 添加账户
let main = document.querySelector("main");
let index = 0;
$("add-user").addEventListener("click", function () {
  let h2 = document.createElement("h2");
  Newdata.push(dataInfo[index]);

  main.appendChild(h2);
  if (flag) {
    $("main").appendChild(h2);
  } else {
    $("main").insertBefore(h2, $("main").lastElementChild);
  }
  for (let k in dataInfo[index]) {
    if (index < dataInfo.length) {
      h2.innerHTML = `
        <strong>${dataInfo[index].name}</strong>
        <span>$ ${dataInfo[index].money.toLocaleString()}</span>
        `;
        
    }
   
  }
  index++;
});

//资金翻倍
$("double").addEventListener("click", function (item) {
  clean();

  Newdata.forEach(function (item) {
    // 数据翻倍 (需要重新赋值,改变原数据)
    item.money = item.money * 2;
    // 渲染页面
    let h2 = document.createElement("h2");
    // `` 模版字符串 es6新语法
    h2.innerHTML = `
    <strong>${item.name}</strong>
    <span>$ ${item.money.toLocaleString()}</span>
    `;
    $("main").appendChild(h2);
  });
});

//查询百万富翁
$("show-millionaire").addEventListener("click", function (item) {
  clean();
  Newdata = Newdata.filter(function (item) {
    return item.money >= 1000000;
  });

  Newdata.forEach(function (item) {
    // 渲染页面
    let h2 = document.createElement("h2");
    // `` 模版字符串 es6新语法
    h2.innerHTML = `
    <strong>${item.name}</strong>
    <span>$ ${item.money.toLocaleString()}</span>
    `;
    $("main").appendChild(h2);
  });
});

//财富榜
$("sort").addEventListener("click", function () {
  clean();
  Newdata.sort(function (a, b) {
    return b.money - a.money;
  });
  Newdata.forEach(function (item) {
    // 渲染页面
    let h2 = document.createElement("h2");
    // `` 模版字符串 es6新语法
    h2.innerHTML = `
    <strong>${item.name}</strong>
    <span>$ ${item.money.toLocaleString()}</span>
    `;
    $("main").appendChild(h2);
  });
});

// 计算总额
$("calculate").addEventListener("click", function () {
  let sum = 0;
  // 累加
  sum = Newdata.reduce(function (total, current, currentIndex, arr) {
    return (total += current.money);
  }, 0);

  let h2 = document.createElement("h2");
  // `` 模版字符串 es6新语法
  h2.innerHTML = `
    <strong>总金额</strong>
    <span>$ ${sum.toLocaleString()}</span>
    `;

  // 判断是否可以继续显示总金额
  if (flag) {
    $("main").appendChild(h2);
    // 关闭状态
    flag = false;
  }
});
